<script setup>
import { ref, reactive, computed, onMounted} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  queryRolePageList,
  addRole,
  updateRole,
  deleteRole,
  getRoleById,
  updateRoleStatus,
  getRolePermissions,
  assignPermissions
} from '@/apis/roleAPI'
// import { useUserStore } from '@/stores/user'
// const userStore=useUserStore;

import { queryPermissionPageList } from '@/apis/permissionAPI'

// 查询参数
const queryParams = reactive({
  pageNo: '',
  pageSize: '',
  roleName: '',
  status: ''
})

// 角色列表数据
const roleList = ref([])
const total = ref(0)
const loading = ref(false)

// 分页列表
// const paginatedList = computed(() => roleList.value)

// 对话框状态
const dialogVisible = ref(false)
const permDialogVisible = ref(false)
const dialogType = ref('add') // add/edit
const currentPage=ref(1);
const pageSize=ref(10);

// 角色表单数据
const roleForm = reactive({
  id: '',
  roleName: '',
  roleLogo: '',
  roleDes: '',
  status: 1
})

// 权限相关数据
const permList = ref([])
const permFilterText = ref('')
const currentRoleId = ref('')
const selectedPerms = ref([])
const permSaving = ref(false)

// 表单引用
const roleFormRef = ref(null)
const permTableRef = ref(null)

// 过滤后的权限列表
const filteredPermList = computed(() => {
  if (!permFilterText.value) {
    return permList.value
  }

  return permList.value.filter(perm =>
    (perm.permissionName && perm.permissionName.includes(permFilterText.value)) ||
    (perm.permissionCode && perm.permissionCode.includes(permFilterText.value))
  )
})

// 页面加载时获取角色列表
onMounted(async () => {
  await loadRoleList();
  // console.log("token",userStore.token);
  // console.log("userInfo",userStore.userInfo);
  // console.log("token",localStorage.getItem(userStore.token));

})

// 加载角色列表
const loadRoleList = async () => {
  loading.value = true
  try {
    queryParams.pageNo=currentPage.value;
    queryParams.pageSize=pageSize.value;
    const res = await queryRolePageList(queryParams)
    roleList.value = res.data.records
    total.value = res.data.total
  } catch (e) {
    ElMessage.error(e.msg || '加载角色列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.pageNo = 1
  loadRoleList()
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  loadRoleList()
}

// 页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNo = val
  loadRoleList()
}

// 新增角色
const handleAdd = () => {
  dialogType.value = 'add'
  // 重置表单
  Object.assign(roleForm, {
    id: '',
    roleName: '',
    roleLogo: '',
    roleDes: '',
    status: 1
  })
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  try {
    const res = await getRoleById(row.id)
    Object.assign(roleForm, {
      id: res.data.id,
      roleName: res.data.roleName,
      roleLogo: res.data.roleLogo,
      roleDes: res.data.roleDes,
      status: res.data.status
    })
    dialogVisible.value = true
  } catch (e) {
    ElMessage.error(e.msg || '获取角色详情失败')
  }
}

// 保存角色
const handleSave = async () => {
  // 表单验证
  await roleFormRef.value.validate()

  try {
    if (dialogType.value === 'add') {
      await addRole(roleForm)
      ElMessage.success('新增成功')
    } else {
      await updateRole(roleForm)
      ElMessage.success('修改成功')
    }
    dialogVisible.value = false
    loadRoleList()
  } catch (e) {
    ElMessage.error(e.msg || '操作失败')
  }
}

// 状态切换
const handleStatusChange = async (row) => {
  try {
    await updateRoleStatus(row.id, row.status)
    ElMessage.success('状态更新成功')
  } catch (e) {
    row.status = row.status === 1 ? 0 : 1 // 失败回滚
    ElMessage.error(e.msg || '状态更新失败')
  }
}

// 删除角色
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色【${row.roleName}】吗？`,
      '确认删除',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteRole(row.id)
    ElMessage.success('删除成功')
    loadRoleList()
  } catch (e) {
    if (e !== 'cancel') {
      ElMessage.error(e.msg || '删除失败')
    }
  }
}

// 分配权限
const handleAssignPerm = async (row) => {
  currentRoleId.value = row.id
  permDialogVisible.value = true
  selectedPerms.value = []
  permFilterText.value = ''

  try {
    // 获取所有权限
    const permRes = await queryPermissionPageList({
      pageNo: 1,
      pageSize: 10
    })

    // 过滤无效数据
    permList.value = permRes.data.records.filter(
      item => item && item.id && item.permissionName
    )

    // 获取角色已有权限
    const rolePermRes = await getRolePermissions(row.id)
    const rolePermIds = rolePermRes.data.map(item => item.id)

    // 等待DOM更新后设置选中状态
    await new Promise(resolve => setTimeout(resolve, 100))

    // 设置表格选中项
    if (permTableRef.value) {
      permList.value.forEach((perm, index) => {
        if (rolePermIds.includes(perm.id)) {
          permTableRef.value.toggleRowSelection(perm, true)
        }
      })
    }
  } catch (e) {
    ElMessage.error(e.msg || '获取权限列表失败')
  }
}

// 权限选择变化
const handlePermSelectionChange = (selection) => {
  selectedPerms.value = selection
}

// 保存权限分配
const handleSavePerm = async () => {
  if (selectedPerms.value.length === 0) {
    ElMessage.warning('请至少选择一个权限')
    return
  }

  permSaving.value = true
  try {
    const permIds = selectedPerms.value.map(perm => perm.id).join(',')
    await assignPermissions(currentRoleId.value, permIds)
    ElMessage.success('权限分配成功')
    permDialogVisible.value = false
  } catch (e) {
    ElMessage.error(e.msg || '权限分配失败')
  } finally {
    permSaving.value = false
  }
}
</script>
<template>
  <div class="container">
    <div class="role-header">
      <div class="search-box">
        <el-select   v-model="queryParams.status"  placeholder="状态"  style="margin-left: 10px; width: 150px;"  clearable  >
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
        <el-button  type="primary"  @click="handleSearch"  style="margin-left: 10px;"  > 搜索  </el-button>
      </div>
      <el-button type="primary"  @click="handleAdd"  icon="Plus" >  新增角色  </el-button>
    </div>

    <el-table   :data="roleList"  border style="width: 100%; margin-top: 20px;" v-loading="loading" >
      <el-table-column prop="id" label="角色ID" width="100"  align="center"  />
      <el-table-column  prop="roleName" label="角色名称"  width="150"  align="center"  />
      <el-table-column  prop="roleLogo"  label="角色标识"  width="150" align="center" />
      <el-table-column  prop="roleDes"  label="角色描述"  align="center"/>
      <el-table-column prop="status"  label="状态"  width="120" align="center"  >
        <template #default="scope">
          <el-switch  v-model="scope.row.status"  :active-value="1"   :inactive-value="0"  @change="handleStatusChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column  prop="createTime"  label="创建时间"  width="180" align="center"  />
      <el-table-column label="操作" width="280"  align="center"   >
        <template #default="scope">
          <el-button text  @click="handleEdit(scope.row)" >  编辑  </el-button>
          <el-button  text  @click="handleAssignPerm(scope.row)"  type="primary"  >  分配权限  </el-button>
          <el-button  text   @click="handleDelete(scope.row)"  type="danger" > 删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination" style="margin-top: 15px; text-align: right;">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="10"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增角色' : '编辑角色'"
      width="500px"
    >
      <el-form :model="roleForm"  ref="roleFormRef"  label-width="100px" >
        <el-form-item  label="角色名称"  prop="roleName" :rules="[{ required: true, message: '请输入角色名称', trigger: 'blur' }]" >
          <el-input v-model="roleForm.roleName" />
        </el-form-item>
        <el-form-item  label="角色标识"  prop="roleLogo" :rules="[{ required: true, message: '请输入角色标识', trigger: 'blur' }]"  >
          <el-input v-model="roleForm.roleLogo" />
        </el-form-item>
        <el-form-item label="角色描述"  prop="roleDes"
        >
          <el-input  v-model="roleForm.roleDes"  type="textarea"  rows="3"
          />
        </el-form-item>
        <el-form-item  label="状态"  prop="status" >
          <el-radio-group v-model="roleForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button  type="primary"  @click="handleSave" >  确认 </el-button>
      </template>
    </el-dialog>

    <!-- 权限分配对话框 - 修改为表格形式 -->
    <el-dialog
      v-model="permDialogVisible"
      title="分配权限"
      width="800px"
    >
      <div class="perm-assign-container">
        <div class="perm-search">
          <el-input  v-model="permFilterText" placeholder="搜索权限名称或代码"  clearable  style="width: 300px; margin-bottom: 15px;" />
        </div>
        <el-table :data="filteredPermList" ref="permTableRef"  style="width: 100%"  height="400"  @selection-change="handlePermSelectionChange"  >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="permissionName" label="权限名称" min-width="150" />
          <el-table-column prop="permissionCode" label="权限代码" width="150" />
          <el-table-column prop="type" label="类型" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.type === 1" type="primary">菜单</el-tag>
              <el-tag v-else-if="scope.row.type === 2" type="success">按钮</el-tag>
              <el-tag v-else-if="scope.row.type === 3" type="info">接口</el-tag>
              <el-tag v-else>未知</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="url" label="路径" min-width="200" show-overflow-tooltip />
        </el-table>
      </div>
      <template #footer>
        <el-button @click="permDialogVisible = false">取消</el-button>
        <el-button  type="primary"  @click="handleSavePerm"  :loading="permSaving"  >  确认分配  </el-button>
      </template>
    </el-dialog>
  </div>
</template>



<style scoped>
.container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  margin: 15px;
}

.role-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f5f5f5;
  flex-wrap: wrap;
  gap: 15px;
}

.search-box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  width: 100%;
  max-width: calc(100% - 120px);
}

.el-table {
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.el-table th {
  background-color: #fafafa !important;
  font-weight: 500 !important;
}

.el-table tr:hover > td {
  background-color: #f9fafc !important;
}

.pagination {
  margin-top: 20px;
  padding-top: 10px;
  border-top: 1px solid #f5f5f5;
}

.el-button {
  transition: all 0.2s ease;
}

.el-dialog {
  border-radius: 6px;
  overflow: hidden;
}

.el-dialog__header {
  background-color: #f5f7fa;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.el-dialog__title {
  font-size: 16px;
  font-weight: 500;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-tag {
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
  border-radius: 4px;
}

.perm-assign-container {
  padding: 10px 0;
}

.perm-search {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 15px;
}

.el-table--scrollable-y .el-table__body-wrapper {
  overflow-y: auto;
}

@media (max-width: 768px) {
  .search-box {
    max-width: 100%;
  }

  .role-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .perm-dialog {
    width: 95% !important;
  }
}
</style>
